package com.qeng.aiwanba.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.CountDownTimer;

import com.qeng.aiwanba.R;
import com.qeng.aiwanba.util.Constants;
import com.qeng.aiwanba.util.LocalHtmlUtil;
import com.qeng.aiwanba.util.Util;

import static com.qeng.aiwanba.util.Constants.localHtmlVersion;

/**
 * Created by lixy on 2017/10/13.
 */

public class WelcomeActivity extends BaseActivity {
    private IntentFilter intentFilter;
    private MyBroadcase myBroadcase;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);

        if(Constants.isLoadHtml) {
            int htmlVersion = LocalHtmlUtil.getHtmlVersion(this,localHtmlVersion);
            LocalHtmlUtil.checkHtmlUpdate(getApplicationContext());
            if(htmlVersion == localHtmlVersion){
                //第一次启动app 需等待下载完成后再进入首页
                Util.showToast(this,getString(R.string.tip_first_start_app));
                registerBroadcast();
                return;
            }
        }

        countDownTimer();
    }

    private void registerBroadcast(){
        myBroadcase = new MyBroadcase();
        intentFilter = new IntentFilter(Constants.BROADCAST_HTML_DOWNLOAD_FINISH);
        registerReceiver(myBroadcase,intentFilter);
    }


    private void countDownTimer(){
        new CountDownTimer(2500,100){

            @Override
            public void onTick(long l) {
            }

            @Override
            public void onFinish() {
                enterActivity();
            }
        }.start();
    }

    private void enterActivity(){
        if(!Constants.isLoadHtml){
            startActivity(new Intent(WelcomeActivity.this,IpSettingActivity.class));
        }else {
            startActivity(new Intent(WelcomeActivity.this, MainActivity.class));
        }
        WelcomeActivity.this.finish();
    }

    @Override
    protected void onDestroy() {
        if(myBroadcase != null) {
            unregisterReceiver(myBroadcase);
        }
        super.onDestroy();
    }

    private class MyBroadcase extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(Constants.BROADCAST_HTML_DOWNLOAD_FINISH)){
                enterActivity();
            }
        }
    }
}
